<template>
    <div class="follower-management-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>粉丝管理</span>
            <div>
              <el-button @click="exportData">导出数据</el-button>
              <el-button type="primary" @click="showAddDialog">添加粉丝关系</el-button>
            </div>
          </div>
        </template>
  
        <!-- 查询表单 -->
        <el-form :model="queryForm" inline>
          <el-form-item label="用户名">
            <el-input v-model="queryForm.userName" placeholder="请输入被关注者用户名" clearable />
          </el-form-item>
          <el-form-item label="粉丝名称">
            <el-input v-model="queryForm.followername" placeholder="请输入粉丝名称" clearable />
          </el-form-item>
          <el-form-item label="关系类型">
            <el-select v-model="queryForm.relationtype" placeholder="请选择关系类型" clearable>
              <el-option label="普通粉丝" :value="1" />
              <el-option label="铁粉" :value="2" />
              <el-option label="好友" :value="3" />
              <el-option label="拉黑" :value="4" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否互关">
            <el-select v-model="queryForm.mutual" placeholder="请选择" clearable>
              <el-option label="是" :value="true" />
              <el-option label="否" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
  
        <!-- 数据表格 -->
        <el-table
          :data="tableData"
          v-loading="loading"
          border
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="被关注用户" width="180">
            <template #default="{ row }">
              <div class="user-info-cell">
                <el-avatar :size="40" :src="row.userAvatar || ''" />
                <div class="user-info">
                  <div class="username">{{ row.userName || `用户ID:${row.userid}` }}</div>
                  <div class="userid">ID: {{ row.userid }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="粉丝用户" width="180">
            <template #default="{ row }">
              <div class="user-info-cell">
                <el-avatar :size="40" :src="row.followeravatar || ''" />
                <div class="user-info">
                  <div class="username">
                    {{ row.followername || `用户ID:${row.followerid}` }}
                    <el-tag v-if="row.followerverified" size="small" type="success">V</el-tag>
                  </div>
                  <div class="userid">ID: {{ row.followerid }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="关系类型" width="120">
            <template #default="{ row }">
              <el-tag :type="relationTypeTag[row.relationtype]">
                {{ relationTypeText[row.relationtype] }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="互动信息" width="180">
            <template #default="{ row }">
              <div class="interact-info">
                <div>互动分: {{ row.interactscore }}</div>
                <div>关注天数: {{ row.followdays }}</div>
                <div v-if="row.lastinteracttime">最后互动: {{ formatTime(row.lastinteracttime) }}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="粉丝标签">
            <template #default="{ row }">
              <el-tag
                v-for="(tag, index) in row.tags"
                :key="index"
                size="small"
                style="margin-right: 5px; margin-bottom: 5px"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="关注时间" width="160">
            <template #default="{ row }">
              {{ formatTime(row.createtime) }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button
                size="small"
                :type="row.relationtype === 4 ? 'success' : 'danger'"
                @click="handleChangeRelation(row)"
              >
                {{ row.relationtype === 4 ? '取消拉黑' : '拉黑' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
  
      <!-- 添加/编辑弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @closed="resetForm"
      >
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="被关注用户" prop="userid">
            <el-select
              v-model="formData.userid"
              filterable
              remote
              reserve-keyword
              placeholder="请输入用户ID或名称"
              :remote-method="searchUser"
              :loading="userSearchLoading"
              @change="handleUserSelect"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="`${item.username} (ID:${item.id})`"
                :value="item.id"
              >
                <div style="display: flex; align-items: center">
                  <el-avatar :size="24" :src="item.avatar" style="margin-right: 10px" />
                  <span>{{ item.username }} (ID:{{ item.id }})</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="粉丝用户" prop="followerid">
            <el-select
              v-model="formData.followerid"
              filterable
              remote
              reserve-keyword
              placeholder="请输入用户ID或名称"
              :remote-method="searchUser"
              :loading="userSearchLoading"
              @change="handleFollowerSelect"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="`${item.username} (ID:${item.id})`"
                :value="item.id"
              >
                <div style="display: flex; align-items: center">
                  <el-avatar :size="24" :src="item.avatar" style="margin-right: 10px" />
                  <span>{{ item.username }} (ID:{{ item.id }})</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="关系类型" prop="relationtype">
            <el-radio-group v-model="formData.relationtype">
              <el-radio :label="1">普通粉丝</el-radio>
              <el-radio :label="2">铁粉</el-radio>
              <el-radio :label="3">好友</el-radio>
              <el-radio :label="4">拉黑</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否互关">
            <el-switch v-model="formData.mutual" />
          </el-form-item>
          <el-form-item label="粉丝标签">
            <el-select
              v-model="formData.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请输入粉丝标签"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注名称">
            <el-input v-model="formData.remark" placeholder="请输入备注名称" />
          </el-form-item>
          <el-form-item label="粉丝等级">
            <el-input-number v-model="formData.followerlevel" :min="0" :max="10" />
          </el-form-item>
          <el-form-item label="接收通知">
            <el-switch v-model="formData.notify" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import request from '../utils/request'
  
  // 关系类型映射
  const relationTypeText = {
    1: '普通粉丝',
    2: '铁粉',
    3: '好友',
    4: '拉黑'
  }
  
  const relationTypeTag = {
    1: '',
    2: 'warning',
    3: 'success',
    4: 'danger'
  }
  
  // 查询表单
  const queryForm = reactive({
    userName: '',
    followername: '',
    relationtype: null,
    mutual: null,
    pageNum: 1,
    pageSize: 10
  })
  
  // 表格数据
  const tableData = ref([])
  const total = ref(0)
  const loading = ref(false)
  
  // 弹窗相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('添加粉丝关系')
  const formRef = ref(null)
  const formData = reactive({
    id: null,
    userid: null,
    username: '',
    userAvatar: '',
    followerid: null,
    followername: '',
    followeravatar: '',
    relationtype: 1,
    mutual: false,
    tags: [],
    remark: '',
    followerlevel: 0,
    notify: true
  })
  
  // 用户搜索相关
  const userOptions = ref([])
  const userSearchLoading = ref(false)
  
  // 表单验证规则
  const rules = {
    userid: [
      { required: true, message: '请选择被关注用户', trigger: 'change' }
    ],
    followerid: [
      { required: true, message: '请选择粉丝用户', trigger: 'change' }
    ],
    relationtype: [
      { required: true, message: '请选择关系类型', trigger: 'change' }
    ]
  }
  
  // 获取粉丝列表
  const getFollowerList = async () => {
    try {
        debugger;
      loading.value = true
      const res = await request.post('/xhs/followinglist/getList', queryForm)
        // 处理 tags 字段转换
        tableData.value = (res.data.records || []).map(item => ({
        ...item,
        tags: item.tags ? JSON.parse(item.tags) : []
        }));
      total.value = res.data.total || 0
    } catch (error) {
      console.error('获取粉丝列表失败:', error)
      ElMessage.error('获取粉丝列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 查询用户 (模拟)
  const searchUser = async (query) => {
    if (!query.trim()) {
      userOptions.value = []
      return
    }
    
    try {
      userSearchLoading.value = true
      const res = await request.post('/user/search', { keyword: query })
      userOptions.value = res.data.list || []
    } catch (error) {
      console.error('搜索用户失败:', error)
      ElMessage.error('搜索用户失败')
    } finally {
      userSearchLoading.value = false
    }
  }
  
  // 处理用户选择
  const handleUserSelect = (userId) => {
    const user = userOptions.value.find(item => item.id === userId)
    if (user) {
      formData.username = user.username
      formData.userAvatar = user.avatar
    }
  }
  
  // 处理粉丝选择
  const handleFollowerSelect = (userId) => {
    const user = userOptions.value.find(item => item.id === userId)
    if (user) {
      formData.followername = user.username
      formData.followeravatar = user.avatar
    }
  }
  
  // 查询
  const handleQuery = () => {
    queryForm.pageNum = 1
    getFollowerList()
  }
  
  // 重置查询
  const resetQuery = () => {
    Object.assign(queryForm, {
      userid: '',
      followerid: '',
      followername: '',
      relationtype: null,
      mutual: null,
      pageNum: 1,
      pageSize: 10
    })
    handleQuery()
  }
  
  // 分页大小变化
  const handleSizeChange = (val) => {
    queryForm.pageSize = val
    getFollowerList()
  }
  
  // 当前页变化
  const handleCurrentChange = (val) => {
    queryForm.pageNum = val
    getFollowerList()
  }
  
  // 显示添加弹窗
  const showAddDialog = () => {
    dialogTitle.value = '添加粉丝关系'
    dialogVisible.value = true
  }
  
  // 编辑
  const handleEdit = (row) => {
    dialogTitle.value = '编辑粉丝关系'
    Object.assign(formData, {
      id: row.id,
      userid: row.userid,
      username: row.username || '',
      userAvatar: row.userAvatar || '',
      followerid: row.followerid,
      followername: row.followername || '',
      followeravatar: row.followeravatar || '',
      relationtype: row.relationtype,
      mutual: row.mutual || false,
      tags: row.tags || [],
      remark: row.remark || '',
      followerlevel: row.followerlevel || 0,
      notify: row.notify !== false
    })
    dialogVisible.value = true
  }
  
  // 改变关系 (拉黑/取消拉黑)
  const handleChangeRelation = (row) => {
    const newRelation = row.relationtype === 4 ? 1 : 4
    const actionText = newRelation === 4 ? '拉黑' : '取消拉黑'
    
    ElMessageBox.confirm(`确定${actionText}用户 "${row.followername || row.followerid}" 吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: newRelation === 4 ? 'warning' : 'info'
    }).then(async () => {
      try {
        await request.post('/xhs/following/updateRelation', {
          id: row.id,
          relationtype: newRelation
        })
        ElMessage.success(`${actionText}成功`)
        getFollowerList()
      } catch (error) {
        console.error(`${actionText}失败:`, error)
        ElMessage.error(`${actionText}失败`)
      }
    }).catch(() => {})
  }
  
  // 导出数据
  const exportData = async () => {
    try {
      loading.value = true
      await request.post('/xhs/following/export', queryForm, {
        responseType: 'blob'
      })
      ElMessage.success('导出任务已开始，请稍后查看下载')
    } catch (error) {
      console.error('导出失败:', error)
      ElMessage.error('导出失败')
    } finally {
      loading.value = false
    }
  }
  
  // 提交表单
  const submitForm = async () => {
    try {
      await formRef.value.validate()
      
      const apiUrl = formData.id ? '/xhs/followinglist/update' : '/xhs/followinglist/add'
      const successMsg = formData.id ? '更新成功' : '添加成功'
      
      const payload = {
        ...formData,
        tags: JSON.stringify(formData.tags)
      }
      
      await request.post(apiUrl, payload)
      ElMessage.success(successMsg)
      dialogVisible.value = false
      getFollowerList()
    } catch (error) {
      console.error('表单提交失败:', error)
      if (error.name !== 'ValidateError') {
        ElMessage.error(error.message || '操作失败')
      }
    }
  }
  
  // 重置表单
  const resetForm = () => {
    formRef.value?.resetFields()
    Object.assign(formData, {
      id: null,
      userid: null,
      username: '',
      userAvatar: '',
      followerid: null,
      followername: '',
      followeravatar: '',
      relationtype: 1,
      mutual: false,
      tags: [],
      remark: '',
      followerlevel: 0,
      notify: true
    })
    userOptions.value = []
  }
  
  // 格式化时间
  const formatTime = (time) => {
    if (!time) return ''
    return new Date(time).toLocaleString()
  }
  
  // 初始化加载数据
  onMounted(() => {
    getFollowerList()
  })
  </script>
  
  <style scoped>
  .follower-management-container {
    padding: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .user-info-cell {
    display: flex;
    align-items: center;
  }
  
  .user-info {
    margin-left: 10px;
    line-height: 1.4;
  }
  
  .user-info .username {
    font-weight: 500;
  }
  
  .user-info .userid {
    font-size: 12px;
    color: #999;
  }
  
  .interact-info {
    font-size: 13px;
    line-height: 1.6;
    color: #666;
  }
  </style>